import { Position } from '../types/game';

// 意境类型
export type MoodType = 'moon' | 'wind' | 'bamboo' | 'lotus' | 'crane' | 'mountain';

// 意境物品接口
export interface MoodItem {
  id: string;
  type: MoodType;
  position: Position;
  createdTime: number;
  lifespan: number; // 存在时间（毫秒）
  collected: boolean;
  value: number; // 收集价值
  rarity: 'common' | 'rare' | 'epic'; // 稀有度
}

// 意境配置
interface MoodConfig {
  name: string;
  description: string;
  baseValue: number;
  lifespan: number;
  spawnWeight: number; // 生成权重
  rarity: 'common' | 'rare' | 'epic';
  color: string;
  symbol: string;
}

// 意境配置数据
const MOOD_CONFIGS: Record<MoodType, MoodConfig> = {
  moon: {
    name: '明月',
    description: '皎洁的月光洒向大地，带来宁静与智慧',
    baseValue: 15,
    lifespan: 30000, // 30秒
    spawnWeight: 20,
    rarity: 'common',
    color: '#E5E7EB',
    symbol: '🌙'
  },
  wind: {
    name: '松风',
    description: '清风徐来，松涛阵阵，令人心旷神怡',
    baseValue: 12,
    lifespan: 25000, // 25秒
    spawnWeight: 25,
    rarity: 'common',
    color: '#10B981',
    symbol: '🌬️'
  },
  bamboo: {
    name: '竹影',
    description: '竹影摇曳，清雅脱俗，象征君子之风',
    baseValue: 20,
    lifespan: 35000, // 35秒
    spawnWeight: 15,
    rarity: 'rare',
    color: '#059669',
    symbol: '🎋'
  },
  lotus: {
    name: '荷香',
    description: '荷花盛开，香远益清，出淤泥而不染',
    baseValue: 25,
    lifespan: 40000, // 40秒
    spawnWeight: 10,
    rarity: 'rare',
    color: '#EC4899',
    symbol: '🪷'
  },
  crane: {
    name: '仙鹤',
    description: '白鹤翩翩，仙风道骨，寓意长寿吉祥',
    baseValue: 40,
    lifespan: 20000, // 20秒
    spawnWeight: 5,
    rarity: 'epic',
    color: '#F59E0B',
    symbol: '🕊️'
  },
  mountain: {
    name: '远山',
    description: '青山如黛，层峦叠嶂，意境深远',
    baseValue: 35,
    lifespan: 45000, // 45秒
    spawnWeight: 8,
    rarity: 'epic',
    color: '#6366F1',
    symbol: '⛰️'
  }
};

// 意境系统类
export class MoodSystem {
  private moodItems: MoodItem[] = [];
  private lastSpawnTime: number = 0;
  private spawnInterval: number = 8000; // 8秒生成间隔
  private maxItems: number = 5; // 最大同时存在的意境物品数量
  private boardWidth: number = 10;
  private boardHeight: number = 9;
  private onMoodCollected: (item: MoodItem) => void = () => {};
  private onMoodExpired: (item: MoodItem) => void = () => {};
  private isPaused: boolean = false;

  constructor(
    boardWidth: number = 10,
    boardHeight: number = 9,
    callbacks: {
      onMoodCollected: (item: MoodItem) => void;
      onMoodExpired: (item: MoodItem) => void;
    }
  ) {
    this.boardWidth = boardWidth;
    this.boardHeight = boardHeight;
    this.onMoodCollected = callbacks.onMoodCollected;
    this.onMoodExpired = callbacks.onMoodExpired;
    this.lastSpawnTime = Date.now();
  }

  // 更新意境系统
  update(deltaTime: number, occupiedPositions: Position[] = []): MoodItem[] {
    if (this.isPaused) return this.moodItems;

    const currentTime = Date.now();
    
    // 移除过期的意境物品
    this.removeExpiredItems(currentTime);
    
    // 尝试生成新的意境物品
    this.trySpawnMoodItem(currentTime, occupiedPositions);
    
    return [...this.moodItems];
  }

  // 移除过期的意境物品
  private removeExpiredItems(currentTime: number): void {
    const expiredItems = this.moodItems.filter(item => 
      !item.collected && (currentTime - item.createdTime) >= item.lifespan
    );
    
    expiredItems.forEach(item => {
      this.onMoodExpired(item);
    });
    
    this.moodItems = this.moodItems.filter(item => 
      item.collected || (currentTime - item.createdTime) < item.lifespan
    );
  }

  // 尝试生成新的意境物品
  private trySpawnMoodItem(currentTime: number, occupiedPositions: Position[]): void {
    // 检查是否到了生成时间
    if (currentTime - this.lastSpawnTime < this.spawnInterval) return;
    
    // 检查是否达到最大数量
    const activeItems = this.moodItems.filter(item => !item.collected);
    if (activeItems.length >= this.maxItems) return;
    
    // 随机决定是否生成（70%概率）
    if (Math.random() > 0.7) {
      this.lastSpawnTime = currentTime;
      return;
    }
    
    // 选择意境类型
    const moodType = this.selectRandomMoodType();
    
    // 选择生成位置
    const position = this.findValidSpawnPosition(occupiedPositions);
    
    if (position) {
      const moodItem = this.createMoodItem(moodType, position, currentTime);
      this.moodItems.push(moodItem);
      this.lastSpawnTime = currentTime;
    }
  }

  // 随机选择意境类型（基于权重）
  private selectRandomMoodType(): MoodType {
    const totalWeight = Object.values(MOOD_CONFIGS).reduce(
      (sum, config) => sum + config.spawnWeight, 0
    );
    
    let random = Math.random() * totalWeight;
    
    for (const [type, config] of Object.entries(MOOD_CONFIGS)) {
      random -= config.spawnWeight;
      if (random <= 0) {
        return type as MoodType;
      }
    }
    
    return 'moon'; // 默认返回明月
  }

  // 寻找有效的生成位置
  private findValidSpawnPosition(occupiedPositions: Position[]): Position | null {
    const maxAttempts = 20;
    
    for (let attempt = 0; attempt < maxAttempts; attempt++) {
      const position: Position = {
        x: Math.floor(Math.random() * this.boardWidth),
        y: Math.floor(Math.random() * this.boardHeight)
      };
      
      // 检查位置是否被占用
      const isOccupied = occupiedPositions.some(pos => 
        pos.x === position.x && pos.y === position.y
      );
      
      // 检查是否与现有意境物品重叠
      const hasExistingMood = this.moodItems.some(item => 
        !item.collected && 
        item.position.x === position.x && 
        item.position.y === position.y
      );
      
      if (!isOccupied && !hasExistingMood) {
        return position;
      }
    }
    
    return null; // 找不到有效位置
  }

  // 创建意境物品
  private createMoodItem(type: MoodType, position: Position, currentTime: number): MoodItem {
    const config = MOOD_CONFIGS[type];
    
    return {
      id: this.generateId(),
      type,
      position,
      createdTime: currentTime,
      lifespan: config.lifespan,
      collected: false,
      value: this.calculateValue(config),
      rarity: config.rarity
    };
  }

  // 计算意境物品价值（基于稀有度和随机因子）
  private calculateValue(config: MoodConfig): number {
    const rarityMultiplier = {
      common: 1,
      rare: 1.5,
      epic: 2.5
    };
    
    const randomFactor = 0.8 + Math.random() * 0.4; // 0.8-1.2倍随机
    
    return Math.floor(config.baseValue * rarityMultiplier[config.rarity] * randomFactor);
  }

  // 收集意境物品
  collectMoodItem(position: Position): { success: boolean; item?: MoodItem; message?: string } {
    const item = this.moodItems.find(item => 
      !item.collected && 
      item.position.x === position.x && 
      item.position.y === position.y
    );
    
    if (!item) {
      return { success: false, message: '此位置没有意境物品' };
    }
    
    // 标记为已收集
    item.collected = true;
    
    // 触发收集回调
    this.onMoodCollected(item);
    
    const config = MOOD_CONFIGS[item.type];
    
    return {
      success: true,
      item,
      message: `收集到${config.name}，获得${item.value}点意境值！`
    };
  }

  // 获取指定位置的意境物品
  getMoodItemAt(position: Position): MoodItem | null {
    return this.moodItems.find(item => 
      !item.collected && 
      item.position.x === position.x && 
      item.position.y === position.y
    ) || null;
  }

  // 获取所有活跃的意境物品
  getActiveMoodItems(): MoodItem[] {
    return this.moodItems.filter(item => !item.collected);
  }

  // 获取已收集的意境物品
  getCollectedMoodItems(): MoodItem[] {
    return this.moodItems.filter(item => item.collected);
  }

  // 获取意境统计
  getMoodStatistics(): {
    totalCollected: number;
    totalValue: number;
    typeStats: Record<MoodType, { count: number; value: number }>;
    rarityStats: Record<string, { count: number; value: number }>;
  } {
    const collected = this.getCollectedMoodItems();
    
    const typeStats: Record<MoodType, { count: number; value: number }> = {
      moon: { count: 0, value: 0 },
      wind: { count: 0, value: 0 },
      bamboo: { count: 0, value: 0 },
      lotus: { count: 0, value: 0 },
      crane: { count: 0, value: 0 },
      mountain: { count: 0, value: 0 }
    };
    
    const rarityStats: Record<string, { count: number; value: number }> = {
      common: { count: 0, value: 0 },
      rare: { count: 0, value: 0 },
      epic: { count: 0, value: 0 }
    };
    
    let totalValue = 0;
    
    collected.forEach(item => {
      typeStats[item.type].count++;
      typeStats[item.type].value += item.value;
      
      rarityStats[item.rarity].count++;
      rarityStats[item.rarity].value += item.value;
      
      totalValue += item.value;
    });
    
    return {
      totalCollected: collected.length,
      totalValue,
      typeStats,
      rarityStats
    };
  }

  // 暂停/恢复系统
  setPaused(paused: boolean): void {
    this.isPaused = paused;
    
    if (!paused) {
      // 恢复时调整时间偏移
      const currentTime = Date.now();
      const pauseDuration = currentTime - this.lastSpawnTime;
      
      // 调整意境物品的创建时间
      this.moodItems.forEach(item => {
        if (!item.collected) {
          item.createdTime += pauseDuration;
        }
      });
      
      this.lastSpawnTime = currentTime;
    }
  }

  // 清理系统
  cleanup(): void {
    this.moodItems = [];
    this.lastSpawnTime = Date.now();
  }

  // 强制生成意境物品（用于测试）
  forceSpawnMoodItem(type: MoodType, position?: Position): MoodItem | null {
    const targetPosition = position || this.findValidSpawnPosition([]);
    
    if (!targetPosition) return null;
    
    const moodItem = this.createMoodItem(type, targetPosition, Date.now());
    this.moodItems.push(moodItem);
    
    return moodItem;
  }

  // 设置生成参数
  setSpawnParameters(interval: number, maxItems: number): void {
    this.spawnInterval = Math.max(1000, interval); // 最小1秒间隔
    this.maxItems = Math.max(1, Math.min(10, maxItems)); // 1-10个物品
  }

  // 生成唯一ID
  private generateId(): string {
    return `mood_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
  }

  // 获取意境配置
  static getMoodConfig(type: MoodType): MoodConfig {
    return MOOD_CONFIGS[type];
  }

  // 获取所有意境配置
  static getAllMoodConfigs(): Record<MoodType, MoodConfig> {
    return { ...MOOD_CONFIGS };
  }
}